package dao

import (
	"fmt"
	"github.com/cn-zhangjie/postgresql-to-struct/pkg/database"
	"github.com/cn-zhangjie/postgresql-to-struct/pkg/settings"
	"github.com/cn-zhangjie/postgresql-to-struct/po"
)

// 根据schema获得所有表信息
func FindAllTableInfo() []po.TableInfo {
	// 返回结果集
	tableInfoSlice := make([]po.TableInfo, 0)
	// 查询并获得列表数据
	err := database.Instance.Select(&tableInfoSlice, `
SELECT pgc.relname              AS NAME,
       obj_description(pgc.oid) AS COMMENT
FROM pg_class AS pgc
         INNER JOIN pg_tables AS pgt ON pgt.tablename = pgc.relname
WHERE pgt.schemaname = $1
  AND pgc.relkind = 'r';
	`, settings.DatabaseSetting.Schema)
	if err != nil {
		fmt.Println("获取表信息失败：", err)
	}
	return tableInfoSlice
}

// 根据表名获得结构信息
func FindOneByTableName(tableName string) []po.TableColumn {
	tableStructSlice := make([]po.TableColumn, 0)
	err := database.Instance.Select(&tableStructSlice, `
SELECT A.attname                            AS name,
       format_type(A.atttypid, A.atttypmod) AS type,
       A.attnotnull                         AS not_null,
       b.description                        AS comment
FROM pg_class C,
     pg_attribute A
         LEFT OUTER JOIN pg_description b ON A.attrelid = b.objoid
         AND A.attnum = b.objsubid,
     pg_type T
WHERE C.relname = $1
  AND A.attnum > 0
  AND A.attrelid = C.oid
  AND A.atttypid = T.oid
ORDER BY A.attnum;
	`, tableName)
	if err != nil {
		fmt.Println("获得表结构失败：", err)
	}
	return tableStructSlice
}
